import { UserModule } from '@/store/modules/user';
import { RouterMount, createRouter } from "uni-simple-router";
import { routes } from './route';

let first: any = null;

/** 创建路由方法 */
const initialRouter = () => createRouter({
  platform: "h5",
  keepUniOriginNav: false,
  h5: {
    vueRouterDev: true,
    // mode: 'hash',
    scrollBehavior: (_to: any, _from: any, savedPosition: any) => {
      if (savedPosition) {
        return savedPosition;
      } else {
        return { x: 0, y: 0 };
      }
    },
  },
  // routerBeforeEach: (_to, _from, next) => {
  //   console.log("+++++routerBeforeEach++++");
  //   next();
  // },
  // routerAfterEach: (_to, _from) => {
  //   console.log("--------routerAfterEach----");
  // },
  detectBeforeLock: (router, to, navType) => {
    console.log('detectBeforeLock > to:', to)
    router.$lockStatus = false;
  },
  routerErrorEach: ({ type, msg }, router) => {
    console.log('routerErrorEach > ', { type, msg });
    // #ifdef H5
    if (type === 2) {
      console.log('Unlock Router ...', router);
      router.$lockStatus = false;
    }
    // #endif
    // #ifdef APP-PLUS
    if (type === 3) {
      router.$lockStatus = false;
      if (!first) {
        first = new Date().getTime();
        uni.showToast({
          title: "再按一次退出应用",
          icon: "none",
          position: "bottom",
          duration: 1000,
        });
        setTimeout(function () {
          first = null;
        }, 1000);
      } else {
        if (new Date().getTime() - first < 1000) {
          plus.runtime.quit();
        }
      }
    }
    // #endif
  },
  routes,
});


/** 白名单，以下地址不会进行路由权限检查 */
const whiteList = ['/login'];

/** 复位路由，该方法会重新创建应用的路由栈 */
export const resetRouter = function () {
  const newRouter = initialRouter();
  console.log("***** Router Reset...");
  (router as any).matcher = (newRouter as any).matcher; // reset router
};

/** 路由实例 */
const router = initialRouter();

router.beforeEach((to, from, next) => {
  console.log("***** Router BeforeEach > to:", to.name);
  if (UserModule.token !== '') {
    console.log('router.beforeEach > has UserToken');
    next();
  } else {
    console.log('router.beforeEach > not UserToken');
    if (whiteList.indexOf(to.path) !== -1) {
      // In the free login whitelist, go directly
      console.log('router.beforeEach > whiteList:', to.path);
      next();
    } else {
      console.log('router.beforeEach > goto /login?redirect:', to.path);
      next({ path: '/login', query: { redirect: `${to.path}` } });
      // next();
    }
  }
  // next(false);
});

router.afterEach((to, _from) => {
  console.log("***** Router AfterEach > to:", to.name);
  document.title = (to.meta as any).title;
});

export { router, RouterMount };
